#pragma once
#include <ctime>
#include <vector>
#include <cassert>
#include <sstream>
#include <memory>
#include "Level.hpp"
#include "Message.hpp"

namespace mylog
{
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void Format(std::ostream &out, const LogMessage &msg) = 0;
    };
    class MsgFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << msg._payload;
        }
    };
    class LevelFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };
    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(std::string timefmt = "%H:%M:%S") : _time_fmt(timefmt)
        {
        }
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char tmp[32];
            strftime(tmp, 31, _time_fmt.c_str(), &t);
            out << tmp;
        }

    private:
        std::string _time_fmt;
    };
    class FileFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << msg._file;
        }
    };
    class LineFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << msg._line;
        }
    };
    class ThreadFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << msg._tid;
        }
    };
    class LoggerFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << msg._logger;
        }
    };
    class TabFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << "\t";
        }
    };
    class NewlineFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << "\n";
        }
    };
    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(std::string str) : _str(str)
        {
        }
        void Format(std::ostream &out, const LogMessage &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    // %d 表示日期 ,包含子格式 {%H:%M:%S}
    // %t 表示线程ID
    // %c 表示日志器名称
    // %f 表示源码文件名
    // %l 表示源码行号
    // %p 表示日志级别
    // %T 表示制表符缩进
    // %m 表示主体消息
    // %n 表示换行
    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n") : _pattern(pattern)
        {
            assert(Parsepatten());
        }
        void Format(std::ostream &out, const LogMessage &msg)
        {
            for (auto &item : _items)
            {
                item->Format(out, msg);
            }
        }
        std::string Format(const LogMessage &msg)
        {
            std::stringstream ss;
            Format(ss, msg);
            return ss.str();
        }

    private:
        bool Parsepatten()
        {
            std::vector<std::pair<std::string, std::string>> fmt_order;
            size_t pos = 0;
            std::string key, val;
            while (pos < _pattern.size())
            {
                if (_pattern[pos] != '%')
                {
                    val += _pattern[pos++];
                    continue;
                }
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val += _pattern[pos];
                    pos += 2;
                    continue;
                }
                if (!val.empty())
                {
                    fmt_order.push_back(make_pair("", val));
                    val.clear();
                }
                pos++;
                if(pos == _pattern.size())
                {
                    std::cout << "%之后没有对应的格式化字符" << std::endl;
                    return false;
                }
                key = _pattern[pos++];
                if(pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos++;
                    while(pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val += _pattern[pos++];
                    }
                    if(pos == _pattern.size())
                    {
                        std::cout << "{}不匹配" << std::endl;
                        return false;
                    }
                    pos++;
                }
                fmt_order.push_back(make_pair(key, val));
                key.clear();
                val.clear();
            }
            for(auto& e : fmt_order)
            {
                _items.push_back(CreateItem(e.first, e.second));
            }
            return true;
        }
        FormatItem::ptr CreateItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<FileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NewlineFormatItem>();
            if (key == "")
                return std::make_shared<OtherFormatItem>(val);
            std::cout << "没有对应的格式化字符%" << key << std::endl;
            abort();
            return FormatItem::ptr();
        }

    private:
        std::string _pattern;
        std::vector<FormatItem::ptr> _items;
    };
}